<?php

namespace system\model;

use houdunwang\model\Model;
use houdunwang\session\Session;
use houdunwang\validate\Validate;

class Admin extends model
{
    //操作的数据表
    protected $table = "admin";

    //登录
    public function login()
    {
        $password = password_hash('post.admin_password', PASSWORD_DEFAULT);
//    	echo $password;die;
        //1.验证数据不能为空
        $data = [
            'admin_username' => q('post.admin_username'),
            'admin_password' => q('post.admin_password'),
            'code' => q('post.code'),
        ];
        //p($data);die;
        $res = Validate::make([
            ['admin_username', 'isnull', '请输入用户名', 3],
            ['admin_password', 'isnull', '请输入密码', 3],
            ['code', 'isnull', '请输入验证码', 3],
        ], $data);
        //2.比对用户名密码是否正确
        $userInfo = $this->where('admin_username', $data['admin_username'])->first();
        if (!$userInfo) {
            return ['valid' => 0, 'msg' => '用户名不正确'];
        }
        //校验密码
//        file_put_contents('./99.php',password_hash($data['admin_password'],PASSWORD_DEFAULT));
        if (!password_verify($data['admin_password'], $userInfo['admin_password'])) {
            return ['valid' => 0, 'msg' => '密码不正确'];
        }
//			$userInfo = $this->where('admin_username',$data['admin_username'])
//				->where('admin_password',password_hash($data['admin_password'],PASSWORD_DEFAULT))
//				->first();
//			if(!$userInfo){
//				return ['valid'=>0,'msg'=>'用户名或者密码不正确'];
//			}
        //3.比对验证码是否正确
        //var_dump(Code::auth( 'code' ));die;
        if (!Code::auth('code')) {
            return ['valid' => 0, 'msg' => '验证码不正确'];
        }
        //4.将当前登录用户信息存入session
        Session::set('admin.admin_id', $userInfo['admin_id']);
        Session::set('admin.admin_username', $userInfo['admin_username']);
        //5.返回成功
        return ['valid' => 1, 'msg' => '登录成功'];
    }

    //修改密码
    public function changePassword($data)
    {
        Validate::make([
            ['admin_password','requied','请输入旧密码',3],
            ['new_password','requied','请输入新密码',3],
            ['retry_password','confirm:new_password','输入有误，请核对新密码',3],
        ]);
        //旧密码验证
        $userInfo = self::find(Session::get('admin.admin_id'));//获取当前登录用户id
        if(!password_verify($data['admin_password'],$userInfo['admin_password'])){
            return ['valid'=>0,'message'=>'原始密码不正确'];
        }
        //密码正确时跳过上面判断，接收并保存将结果赋值出去
        $userInfo->admin_password = password_hash($data['new_password'],PASSWORD_DEFAULT);
        $userInfo->save();
        return ['valid'=>1,'message'=>'修改成功'];
    }

}